package com.iotp.controller.user;

import com.alibaba.druid.sql.ast.statement.SQLForeignKeyImpl;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.iotp.entity.base.DataMessage;
import com.iotp.entity.crop.Crop;
import com.iotp.entity.crop_type.CropType;
import com.iotp.entity.disease_area.DiseaseArea;
import com.iotp.entity.disease_name.DiseaseName;
import com.iotp.entity.disease_trait.DiseaseTrait;
import com.iotp.entity.disease_type.DiseaseType;
import com.iotp.entity.expert.Expert;
import com.iotp.entity.expert_type.ExpertType;
import com.iotp.entity.knowledge.Knowledge;
import com.iotp.entity.knowledge.KnowledgeWithBLOBs;
import com.iotp.entity.knowledge_type.KnowledgeType;
import com.iotp.entity.leave_message.LeaveMessage;
import com.iotp.entity.live.Live;
import com.iotp.entity.online_exchange.OnlineExchange;
import com.iotp.entity.paste.Paste;
import com.iotp.entity.paste.PasteWithBLOBs;
import com.iotp.entity.user_statistics.UserStatistics;
import com.iotp.service.crop.CropService;
import com.iotp.service.crop_type.CropTypeService;
import com.iotp.service.disease_area.DiseaseAreaService;
import com.iotp.service.disease_name.DiseaseNameService;
import com.iotp.service.disease_trait.DiseaseTraitService;
import com.iotp.service.disease_type.DiseaseTypeService;
import com.iotp.service.expert.ExpertService;
import com.iotp.service.expert_type.ExpertTypeService;
import com.iotp.service.knowledge.KnowledgeService;
import com.iotp.service.leave_message.LeaveMessageService;
import com.iotp.service.live.LiveService;
import com.iotp.service.online_exchange.OnlineExchangeService;
import com.iotp.service.paste.PasteService;
import com.iotp.service.user_statistics.UserStatisticsService;
import com.iotp.utils.zb.ChannelManagementUtil;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class UserIndexController {
    private Logger logger = LoggerFactory.getLogger(UserIndexController.class);

    @Value("${pic.pastePath}")
    private String pastePath;
    @Autowired
    private CropTypeService cropTypeService;
    @Autowired
    private CropService cropService;
    @Autowired
    private DiseaseTypeService diseaseTypeService;
    @Autowired
    private DiseaseNameService diseaseNameService;
    @Autowired
    private ExpertService expertService;
    @Autowired
    private KnowledgeService knowledgeService;
    @Autowired
    private LeaveMessageService leaveMessageService;
    @Autowired
    private ExpertTypeService expertTypeService;
    @Autowired
    private PasteService pasteService;
    @Autowired
    private DiseaseAreaService diseaseAreaService;
    @Autowired
    private DiseaseTraitService diseaseTraitService;
    @Autowired
    private OnlineExchangeService onlineExchangeService;
    @Autowired
    private LiveService liveService;
    @Autowired
    private UserStatisticsService userStatisticsService;
    /**
     * 首页
     * @return
     */
    @GetMapping("/index")
    public String toUserIndexPage(HttpServletRequest request){
        //作物类型
        CropType query = new CropType();
        query.setState(1);
        List<CropType> cropTypeList = this.cropTypeService.queryList(query);
        request.setAttribute("cropTypeList", cropTypeList);
        //专家
        List<Expert> experts = this.expertService.queryLimit();
        if( experts != null && !experts.isEmpty()){
            for(Expert e : experts){
                if(e.getHeadImgUrl() == null || "".equals(e.getHeadImgUrl())){
                    if(null == e.getHeadImgUrl() || "".equals(e.getHeadImgUrl())){
                        e.setHeadImgUrl("/pestdiagnosis/images/user/zb.jpg");
                    }
                }
            }
        }
        request.setAttribute("experts", experts);
//        List<Expert> list1 = experts.subList(0,4);
//        List<Expert> list2 = experts.subList(4,8);
//        request.setAttribute("experts1", list1);
//        request.setAttribute("experts2", list2);
        //防治案例  专家指导   农事提示  常见病虫害
        List<Knowledge> fzal = this.knowledgeService.queryByTypeId(3L);
        request.setAttribute("fzal", fzal);
        List<Knowledge> zjzd = this.knowledgeService.queryByTypeId(2L);
        request.setAttribute("zjzd", zjzd);
        List<Knowledge> nsts = this.knowledgeService.queryByTypeId(1L);
        request.setAttribute("nsts", nsts);
        List<Knowledge> cjbch = this.knowledgeService.queryByTypeId(4L);
        request.setAttribute("cjbch", cjbch);
        //农作物类型
        List<Crop> crops = this.cropService.queryList(new Crop());
        List<Crop> dtzw = new ArrayList<>();
        List<Crop> sczw = new ArrayList<>();
        List<Crop> gszp = new ArrayList<>();
        crops.stream().forEach(item->{
            if(item.getCropTypeId() == 1){
                dtzw.add(item);
            }else if(item.getCropTypeId() == 2){
                sczw.add(item);
            }else{
                gszp.add(item);
            }
        });
        DiseaseType dt_query = new DiseaseType();
        dt_query.setState(1);
        List<DiseaseType> dt = this.diseaseTypeService.queryList(dt_query);
        request.setAttribute("dt", dt);
        request.setAttribute("dtzw", dtzw);
        request.setAttribute("sczw", sczw);
        request.setAttribute("gszp", gszp);
        //全部专家
        List<Expert> experts1 = this.expertService.queryList(new Expert());
        request.setAttribute("experts1", experts1);

        return "user/index";
    }

    @PostMapping("/u/addLeaveMessage")
    @ResponseBody
    public DataMessage addLeaveMessage(LeaveMessage leaveMessage){
        leaveMessage.setCreateTime(System.currentTimeMillis());
        leaveMessage.setUpdateTime(System.currentTimeMillis());
        Long id = this.leaveMessageService.add(leaveMessage);
        DataMessage dm = new DataMessage();
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("添加成功");
        return dm;
    }



    /**
     * 根据分类id查询作物
     * @param id
     * @return
     */
    @PostMapping("/u/getCropById")
    @ResponseBody
    public DataMessage getCropById(Long id){
        DataMessage dm = new DataMessage();
        if(id == null || id.longValue() == 0L){
            dm.setResult(1);
            dm.setData(null);
            dm.setMessage("请选择作物分类");
        }else{
            Crop query = new Crop();
            query.setState(1);
            query.setCropTypeId(id);
            List<Crop> crops = this.cropService.queryList(query);
            dm.setResult(0);
            dm.setData(crops);
            dm.setMessage(null);
        }
        return dm;
    }

    /**
     * 查询病害类别
     * @return
     */
    @PostMapping("/u/getDiseaseType")
    @ResponseBody
    public DataMessage getDiseaseType(){
        DiseaseType query = new DiseaseType();
        query.setState(1);
        List<DiseaseType> diseaseTypes = this.diseaseTypeService.queryList(query);
        DataMessage dm = new DataMessage();
        dm.setResult(0);
        dm.setData(diseaseTypes);
        dm.setMessage(null);
        return dm;
    }

    /**
     * 查询病害名称
     * @param cropId
     * @param diseaseTypeId
     * @return
     */
    @PostMapping("/u/getDiseaseName")
    @ResponseBody
    public DataMessage getDiseaseName(Long cropId, Long diseaseTypeId){
        DiseaseName query = new DiseaseName();
        query.setCropId(cropId);
        query.setTypeId(diseaseTypeId);
        List<DiseaseName> diseaseNames = this.diseaseNameService.queryList(query);
        DataMessage dm = new DataMessage();
        dm.setResult(0);
        dm.setData(diseaseNames);
        dm.setMessage(null);
        return dm;
    }

    /**
     * 二级页面
     * @return
     */
    @GetMapping("/u/second")
    public String toUserMain(String flag, String cropTypeId,String cropId,String typeId,String typeNameId,
                             String dtzwId, String sczwId, String gszpId,HttpServletRequest request){
        request.setAttribute("flag",flag);
        if("8".equals(flag)){
            request.setAttribute("cropTypeId", cropTypeId);
            request.setAttribute("cropId", cropId);
            request.setAttribute("typeId", typeId);
            request.setAttribute("typeNameId", typeNameId);
        }else if("7".equals(flag)){
            request.setAttribute("dazwId", dtzwId);
            request.setAttribute("sczwId", sczwId);
            request.setAttribute("gszpId", gszpId);
        }
        return "user/second/main";
    }

    /**
     * 二级页面首页
     * @return
     */
    @GetMapping("/u/toCommon")
    public String toCommon(HttpServletRequest request){
//        List<Expert> experts = this.expertService.queryList(new Expert());
//        request.setAttribute("zj", null == experts?0:experts.size());
        List<PasteWithBLOBs> pastes = this.pasteService.queryList(new PasteWithBLOBs());
        request.setAttribute("ft", null == pastes?0:pastes.size());
        List<LeaveMessage> leaveMessages = this.leaveMessageService.queryList(new LeaveMessage());
        request.setAttribute("ly", null==leaveMessages?0:leaveMessages.size());
        List<KnowledgeWithBLOBs> knowledges = this.knowledgeService.queryList(new KnowledgeWithBLOBs());
        request.setAttribute("zs", null==knowledges?0:knowledges.size());
        List<LeaveMessage> res = new ArrayList<>();
        if(leaveMessages !=null && !leaveMessages.isEmpty()){
            for(LeaveMessage l : leaveMessages){
                if(null == l.getReplyContent() || "".equals(l.getReplyContent())){
                    l.setReplyContent("暂无回复");
                }
                res.add(l);
            }
        }
        request.setAttribute("leaveMessages", res);
        return "user/common/common_center";
    }

    /**
     * 直播列表
     * @return
     */
    @GetMapping("/u/liveList")
    public String toLiveList(HttpServletRequest request){
        List<Live> list = this.liveService.queryList(new Live());
        if(list != null && !list.isEmpty()){
            for(Live l : list){
                JSONObject json = ChannelManagementUtil.getStatsChannel(l.getcId());
                //0：空闲； 1：直播； 2：禁用； 3：直播录制
                if(json.getInteger("code") == 200){
                    l.setStatus(JSONObject.parseObject(json.getString("ret")).getInteger("status"));
                }else{
                    l.setStatus(0);
                }
            }
            request.setAttribute("list", list);
        }else{
            list = new ArrayList<>();
            request.setAttribute("list", list);
        }
        return "user/second/expert/live_list";
    }

    /**
     * 咨询专家
     * @return
     */
    @GetMapping("/u/consultExpert")
    public String toConsultExpert(){
        return "user/second/expert/consult_expert";
    }

    /**
     * 专家列表
     * @return
     */
    @GetMapping("/u/expertList")
    public String toExpertList(HttpServletRequest request, String expertName, String typeId){
        List<ExpertType> expertTypes = this.expertTypeService.queryList(new ExpertType());
        request.setAttribute("types", expertTypes);
        Expert query = new Expert();
        if(!StringUtils.isEmpty(expertName)){
            query.setName(expertName);
        }
        if(!StringUtils.isEmpty(typeId) && !"0".equals(typeId)){
            query.setExpertType(Long.parseLong(typeId));
        }
        List<Expert> experts = this.expertService.queryList(query);
        if(null != experts && !experts.isEmpty()){
            for(Expert e : experts){
                if(null == e.getHeadImgUrl() || "".equals(e.getHeadImgUrl())){
                    e.setHeadImgUrl("/pestdiagnosis/images/user/zb.jpg");
                }
            }
        }

        List<LeaveMessage> l = this.leaveMessageService.queryList(new LeaveMessage());

        Map<String, Integer> m = new HashMap<>();//未回复
        Map<String, Integer> m2 = new HashMap<>();//已回复
        Map<String, Integer> m3 = new HashMap<>();//已回复/(未回复+已回复)


        if(l == null || l.isEmpty()){
            for(Expert e : experts){
                e.setDfl("0%");
            }
        }else{
            for(LeaveMessage le : l){
                if(StringUtils.isEmpty(le.getReplyContent())){
                    //未回复
                    if(m.containsKey(le.getId()+"")){
                        Integer num = m.get(le.getId()+"");
                        m.put(le.getId()+"", num+1);
                    }else{
                        m.put(le.getId()+"", 1);
                    }
                }else{
                    //已回复
                    if(m2.containsKey(le.getId()+"")){
                        Integer num = m2.get(le.getId()+"");
                        m2.put(le.getId()+"", num+1);
                    }else{
                        m2.put(le.getId()+"", 1);
                    }
                }

            }
            for(Map.Entry<String, Integer> ent : m.entrySet()){
                //便利未回复的
                Integer w_num = ent.getValue();
                if(m2.containsKey(ent.getKey())){
                    Integer y_num = m2.get(ent.getKey());
                    Double hfl = Double.valueOf(y_num)/Double.valueOf(w_num+y_num);
                    Integer lv = Integer.parseInt(new java.text.DecimalFormat("0").format(hfl))*100;
                    m3.put(ent.getKey(), lv);
                }else{
                    m3.put(ent.getKey(),0);
                }
            }
            for(Map.Entry<String, Integer> ent2: m2.entrySet()){
                //便利已回复的
                Integer y_num = ent2.getValue();
                if(m3.containsKey(ent2.getKey())){

                }else{
                    m3.put(ent2.getKey(),100);
                }
            }

            for(Expert e : experts){
                if(m3.containsKey(e.getId()+"")){
                    e.setDfl(m3.get(e.getId()+"")+"%");
                }else{
                    e.setDfl("0%");
                }
            }
        }

        request.setAttribute("experts", experts);
        return "user/second/expert/expert_list";
    }

    /**
     * 留言列表
     * @return
     */
    @GetMapping("/u/leaveList")
    public String toLeaveList(HttpServletRequest request, String expertName, String typeId){
        LeaveMessage query = new LeaveMessage();
        if(!StringUtils.isEmpty(expertName)){
            query.setConsultExpertName(expertName);
        }
        if(!StringUtils.isEmpty(typeId) && !"0".equals(typeId)){
            query.setConsultExpertId(Long.parseLong(typeId));
        }

        DiseaseType dt_query = new DiseaseType();
        dt_query.setState(1);
        List<DiseaseType> dt = this.diseaseTypeService.queryList(dt_query);
        request.setAttribute("dt", dt);

        List<LeaveMessage> leaveMessages = this.leaveMessageService.queryList(query);
        request.setAttribute("leaveMessages",leaveMessages);
        return "user/second/expert/leave_list";
    }

    /**
     * 个人中心
     * @return
     */
    @GetMapping("/u/center")
    public String toCenter(){
        return "user/second/my/center";
    }

    /**
     * 游客登录
     * @return
     */
    @GetMapping("/u/login")
    public String toLogin(){
        return "user/second/my/login";
    }

    /**
     * 游客注册
     * @return
     */
    @GetMapping("/u/register")
    public String toRegister(){
        return "user/second/my/register";
    }

    /**
     * 忘记密码
     * @return
     */
    @GetMapping("/u/forgetpwd")
    public String toForgetpwd(){
        return "user/second/my/forgetpwd";
    }

    /**
     * 发帖提问
     * @return
     */
    @GetMapping("/u/addPaste")
    public String toAddPaste(HttpServletRequest request){
        DiseaseType dt_query = new DiseaseType();
        dt_query.setState(1);
        List<DiseaseType> dt = this.diseaseTypeService.queryList(dt_query);
        request.setAttribute("dt", dt);
        return "user/second/paste/add_paste";
    }

    /**
     * 疑难交流
     * @return
     */
    @GetMapping("/u/ynPaste")
    public String toYnPaste(HttpServletRequest request){
        DiseaseType dt_query = new DiseaseType();
        dt_query.setState(1);
        List<DiseaseType> dt = this.diseaseTypeService.queryList(dt_query);
        request.setAttribute("dt", dt);
        return "user/second/paste/yn_paste";
    }

    /**
     * 发帖
     * @param name
     * @param typeId
     * @param typeName
     * @param content
     * @return
     */
    @PostMapping("/u/add_paste")
    @ResponseBody
    public DataMessage add_paste(String name, String typeId, String typeName, String content){
        DataMessage dm = new DataMessage();
        if(StringUtils.isEmpty(name) || StringUtils.isEmpty(typeId) || StringUtils.isEmpty(typeName) || StringUtils.isEmpty(content)){
            dm.setResult(1);
            dm.setData(null);
            dm.setMessage("参数错误");
        }else{
            PasteWithBLOBs add = new PasteWithBLOBs();
            add.setName(name);
            add.setPestTypeId(Long.parseLong(typeId));
            add.setPestTypeName(typeName);
            add.setContent(content);
            add.setCreateTime(System.currentTimeMillis());
            add.setLookNum(1);
            this.pasteService.add(add);
            dm.setResult(0);
            dm.setData(null);
            dm.setMessage("添加成功");
        }
        return dm;
    }

    /**
     * 发帖列表
     * @return
     */
    @GetMapping("/u/pasteList")
    public String toPasteList(HttpServletRequest request, String name, String typeId){
        PasteWithBLOBs query = new PasteWithBLOBs();
        if(!StringUtils.isEmpty(name)){
            query.setName(name);
        }
        if(!StringUtils.isEmpty(typeId) && !"0".equals(typeId)){
            query.setPestTypeId(Long.parseLong(typeId));
        }
        DiseaseType dt_query = new DiseaseType();
        dt_query.setState(1);
        List<DiseaseType> dt = this.diseaseTypeService.queryList(dt_query);
        request.setAttribute("dt", dt);
        List<PasteWithBLOBs> pastes = this.pasteService.queryList(query);
        request.setAttribute("pastes", pastes);
        return "user/second/paste/paste_list";
    }

    /**
     * 在线诊断
     * @return
     */
    @GetMapping("/u/pestDiagnosis")
    public String toPestDiagnosis(HttpServletRequest request, String cropId, String daId, String dtId){
        //作物分类
        CropType query = new CropType();
        query.setState(1);
        List<CropType> cropTypeList = this.cropTypeService.queryList(query);
        request.setAttribute("cropTypeList", cropTypeList);

        //病害部位
        DiseaseArea query_ad = new DiseaseArea();
        query_ad.setState(1);
        List<DiseaseArea> diseaseAreas = this.diseaseAreaService.queryList(query_ad);
        request.setAttribute("diseaseAreas", diseaseAreas);
        //病害特性
        DiseaseTrait query_dt = new DiseaseTrait();
        query_dt.setState(1);
        List<DiseaseTrait> diseaseTraits = this.diseaseTraitService.queryList(query_dt);
        List<DiseaseTrait> diseaseTraits1 = new ArrayList<>();
        List<DiseaseTrait> diseaseTraits2 = new ArrayList<>();
        if(diseaseTraits == null || diseaseTraits.isEmpty()){

        }else{
            if(diseaseTraits.size() == 1){
                diseaseTraits1 = diseaseTraits;
            }else{
                diseaseTraits1 = diseaseTraits.subList(0,diseaseTraits.size()/2);
                diseaseTraits2 = diseaseTraits.subList(diseaseTraits.size()/2,diseaseTraits.size());
            }
        }

        request.setAttribute("diseaseTraits1", diseaseTraits2);
        request.setAttribute("diseaseTraits2", diseaseTraits1);

        //1：农事2：专家3：防治4：常见5.：问题
        KnowledgeWithBLOBs k_query = new KnowledgeWithBLOBs();
        k_query.setkTypeId(5L);
        k_query.setState(2);

        if(!StringUtils.isEmpty(cropId)){
            k_query.setCropIds(cropId);
        }
        if(!StringUtils.isEmpty(daId)){
            k_query.setDiseaseAreaIds(daId);
        }
        if(!StringUtils.isEmpty(dtId)){
            k_query.setDiseaseTraitIds(dtId);
        }
        List<KnowledgeWithBLOBs> knowledgeWithBLOBs = this.knowledgeService.queryList(k_query);
        request.setAttribute("knowledgeWithBLOBs",knowledgeWithBLOBs);

        return "user/second/pest/pest_diagnosis";
    }

    /**
     * 病虫害查询
     * @return
     */
    @GetMapping("/u/pestSearch")
    public String toPestSearch(HttpServletRequest request,  String cropId,  String typeNameId){
        //作物类型
        CropType query = new CropType();
        query.setState(1);
        List<CropType> cropTypeList = this.cropTypeService.queryList(query);
        //病害分类
        DiseaseType query_dt = new DiseaseType();
        query_dt.setState(1);
        List<DiseaseType> diseaseTypes = this.diseaseTypeService.queryList(query_dt);
        request.setAttribute("diseaseTypes", diseaseTypes);

        //1：农事2：专家3：防治4：常见5.：问题
        KnowledgeWithBLOBs k_query = new KnowledgeWithBLOBs();
        k_query.setkTypeId(5L);
        k_query.setState(2);

        if(!StringUtils.isEmpty(cropId)){  //作物id
            k_query.setCropIds(cropId);
        }
        if(!StringUtils.isEmpty(typeNameId)){ //病害名称id
            k_query.setDiseaseNameIds(typeNameId);
        }
        List<KnowledgeWithBLOBs> knowledgeWithBLOBs = this.knowledgeService.queryList(k_query);
        request.setAttribute("knowledgeWithBLOBs",knowledgeWithBLOBs);

        request.setAttribute("cropTypeList", cropTypeList);
        return "user/second/pest/pest_search";
    }

    /**
     * 专家指导
     * @return
     */
    @GetMapping("/u/expertGuide")
    public String toExpertGuide(HttpServletRequest request, String kName){
        //1：农事2：专家3：防治4：常见5.：问题
        KnowledgeWithBLOBs k = new KnowledgeWithBLOBs();
        k.setkTypeId(2L);//防治案例
        k.setState(2);//审核通过
        if(!StringUtils.isEmpty(kName)){
            k.setkName(kName);
        }
        List<KnowledgeWithBLOBs> knowledges = this.knowledgeService.queryList(k);
        request.setAttribute("knowledges", knowledges);
        return "user/second/problem/expert_guide";
    }
    /**
     * 农事提示
     * @return
     */
    @GetMapping("/u/farmingHint")
    public String toFarmingHint(HttpServletRequest request, String kName){
        //1：农事2：专家3：防治4：常见5.：问题
        KnowledgeWithBLOBs k = new KnowledgeWithBLOBs();
        k.setkTypeId(1L);//防治案例
        k.setState(2);//审核通过
        if(!StringUtils.isEmpty(kName)){
            k.setkName(kName);
        }
        List<KnowledgeWithBLOBs> knowledges = this.knowledgeService.queryList(k);
        request.setAttribute("knowledges", knowledges);
        return "user/second/problem/farming_hint";
    }

    /**
     * 防治案例
     * @return
     */
    @GetMapping("/u/treatmentCases")
    public String toTreatmentCases(HttpServletRequest request, String kName){
        //1：农事2：专家3：防治4：常见5.：问题
        KnowledgeWithBLOBs k = new KnowledgeWithBLOBs();
        k.setkTypeId(3L);//防治案例
        k.setState(2);//审核通过
        if(!StringUtils.isEmpty(kName)){
            k.setkName(kName);
        }
        List<KnowledgeWithBLOBs> knowledges = this.knowledgeService.queryList(k);
        request.setAttribute("knowledges", knowledges);
        return "user/second/problem/treatment_cases";
    }

    /**
     * 知识详情页面
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/u/details/{id}")
    public String toKnowledge(@PathVariable("id") Long id, HttpServletRequest request){
        KnowledgeWithBLOBs k = this.knowledgeService.queryById(id);
        request.setAttribute("k", k);
        return "user/second/problem/problem_details";
//        return "user/second/paste/paste_details";
    }

    /**
     * 常见病虫害
     * @return
     */
    @GetMapping("/u/commonPest")
    public String toCommonPest(HttpServletRequest request, String kName){
        //1：农事2：专家3：防治4：常见5.：问题
        KnowledgeWithBLOBs k = new KnowledgeWithBLOBs();
        k.setkTypeId(4L);//防治案例
        k.setState(2);//审核通过
        if(!StringUtils.isEmpty(kName)){
            k.setkName(kName);
        }
        List<KnowledgeWithBLOBs> knowledges = this.knowledgeService.queryList(k);
        request.setAttribute("knowledges", knowledges);
        return "user/second/problem/common_pest";
    }

    /**
     * 发帖提问详情页面
     * @return
     */
    @GetMapping("/u/pasteDetails")
    public String pasteDetails(){
        return "user/second/paste/paste_details";
    }

    /**
     * 在线咨询
     * @param content
     * @param expertId
     * @return
     */
    @PostMapping("/u/sendMes")
    @ResponseBody
    public DataMessage sendMes(String content, String expertId){
        DataMessage dm = new DataMessage();
        OnlineExchange add = new OnlineExchange();
        add.setConsultContent(content);
        add.setToId(Long.parseLong(expertId));
        add.setCreateTime(System.currentTimeMillis());
        add.setUpdateTime(System.currentTimeMillis());
        Long id = this.onlineExchangeService.add(add);
        dm.setResult(0);
        dm.setData(id);
        dm.setMessage("发送成功");
        return dm;
    }

    /**
     * 查询在线咨询的回复信息
     * @param ids  如果已回复，查询是不在传回复的id
     * @return
     */
    @PostMapping("/u/queryMes")
    @ResponseBody
    public DataMessage queryMes(String ids){
        DataMessage dm = new DataMessage();
        List<OnlineExchange> res = new ArrayList<>();
        String[] idarr = ids.split(",");
        for(String id : idarr){
            OnlineExchange item = this.onlineExchangeService.queryById(Long.parseLong(id));
            if(!StringUtils.isEmpty(item.getReplyContent())){
                res.add(item);
            }
        }
        dm.setResult(0);
        dm.setData(res);
        dm.setMessage("查询成功");
        return dm;
    }

    @GetMapping("/u/toLiveDetail")
    public String toLiveDetail(HttpServletRequest request, String url){
        try {
            request.setAttribute("url", URLDecoder.decode(url, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "user/second/expert/live_detail";
    }


    /**
     * 收藏列表
     * @param request
     * @param ids
     * @return
     */
    @GetMapping("/u/sclist")
    public String scList(HttpServletRequest request, String ids){
        List<KnowledgeWithBLOBs> list = new ArrayList<>();
        if(StringUtils.isEmpty(ids)){
           request.setAttribute("knowledges", list);
        }else{
            String[] arr =ids.split(",");
            Set s = new TreeSet();
            for(String i : arr){
                s.add(i);
            }
            List l = new ArrayList(s);
            list = this.knowledgeService.querySc(l);
            request.setAttribute("knowledges", list);
        }
        return "user/second/my/sc";
    }

    /**
     *
     * 获取专家明细
     * @param id
     * @return
     */
    @PostMapping("/u/getExpertInfo")
    @ResponseBody
    public DataMessage getExpertInfo(String id){
        DataMessage dm = new DataMessage();

        Expert e = this.expertService.queryById(Long.parseLong(id));
        dm.setResult(0);
        dm.setData(e);
        dm.setMessage("获取成功");

        return dm;
    }

    /**
     * 记录IP
     * @param ip
     * @return
     */
    @PostMapping("/u/addIp")
    @ResponseBody
    public DataMessage addIp(String ip){
        DataMessage dm = new DataMessage();
        if(null != ip && !"".equals(ip)){
            UserStatistics u = new UserStatistics();
            u.setIp(ip);
            this.userStatisticsService.add(u);
        }
        dm.setResult(0);
        dm.setData(null);
        dm.setMessage("添加成功");
        return dm;
    }

    @GetMapping("/u/pd")
    public String toPd(){
        return "user/second/paste/paste_details";
    }





}
